﻿/*-----------------------------------------------------------------------
 * <copyright file="USEfficSelContainer.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary> 
 *          USEfficSelContainer  UNIT/STAFF 别 的稼动率选择框
 *          作成日：07/14/2010
 *                  子窗体返回列表值： 
 *                  ClientDataList.CheckOpUnitList（选择部分UNIT时，记录UNIT号
 *                                                  -全局- 没有单引号，没有逗号）
 *                  08/11/2010 增加 数据导出功能（除了SV和QC都可以使用这个功能）
 *                  10/15/2010 增加 日志中记录用户查询条件。
 * </summary>
 *-----------------------------------------------------------------------
 */
namespace Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl
{
    using System;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFCommonQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Command = Orid.Management.Statistics.OperatorUnitMangement.Command;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;

    /// <summary>
    /// 查询区域控件 USEfficSelContainer
    /// </summary>
    public partial class USEfficSelContainer : UserControl
    {
        #region 全局变量

        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " UINT别全员别查询公用框USEfficSelContainer ";

        /// <summary>
        /// 记录当前选择的 DockPanel控件名
        /// </summary>
        private string strDockPanelName = string.Empty;

        /// <summary>
        /// 日志服务定义 wcfLogClient
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient;

        /// <summary>
        /// 查询子窗体 UnitSelChildWin
        /// </summary>
        private childWindow.UnitSelChildWin unitSelect;

        /// <summary>
        /// 消息子窗体 errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 获取SV或SSV的组别
        /// </summary>
        private WCFServers.WCFCommonQueryRef.WCFCommonQueryClient wcfCommonQueryClient;

        /// <summary>
        /// 查询命令(queryCcommand) 导出命令(exportComand) 
        /// </summary>
        private Command.ICommand queryCcommand = null, exportComand = null;

        /// <summary>
        /// 开始日期。用于计算DataGrid表头
        /// </summary>
        /// <value> 08/20/2010 ADD </value>
        public DateTime StartDataTime = System.DateTime.Now;

        /// <summary>
        /// 记录用户查询条件
        /// </summary>
        /// <value>10/15/2010 Add</value>
        public string WhereIntorLogs
        {
            get;
            set;
        }

        #endregion 全局变量


        /// <summary>
        /// 构造函数 USEfficSelContainer
        /// </summary>
        public USEfficSelContainer()
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme(LayoutRoot);
            //Accordion 时的Border 控件 引用主题
            ((App)Application.Current).SetTheme(bAccordionItemBorder);

            this.InitField();

            this.Loaded += new RoutedEventHandler(USEfficSelContainer_Loaded);

            // --弹出子窗体--
            this.btnOPID.Click += new RoutedEventHandler(this.BtnOPID_Click);

            // 子窗体关闭事件
            this.unitSelect.Closed += new EventHandler(this.UnitSelect_Closed);

            // 查询符合条件的OP信息
            this.btnUnitSelect.Click += new RoutedEventHandler(BtnUnitSelect_Click);

            // 开始日期(DatePicker)
            this.dpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(this.DpDateFrom_SelectedDateChanged);

            // 结束日期(DatePicker)
            this.dpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(this.DpDateTo_SelectedDateChanged);

            //数据导出
            this.btnExport.Click += new RoutedEventHandler(this.BtnExport_Click);

            //查询SV或SSV的组别(委托)
            this.wcfCommonQueryClient.SelSvUnitInfoCompleted += new EventHandler<SelSvUnitInfoCompletedEventArgs>(wcfCommonQueryClient_SelSvUnitInfoCompleted);
            
            //设置 查询界面 的 查询按钮 数据导出 初始化可用
            this.btnUnitSelect.IsEnabled = true;
            this.btnExport.IsEnabled = true;

            //// 如果不是 SV或QC，显示导出按钮 -- 08/11/2010-- add
            //if (!(ClientUserInfor.RoleName.ToUpper().Trim().Equals("SV") || ClientUserInfor.RoleName.ToUpper().Trim().Equals("QC")))
            //{
            //    this.btnExport.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    this.btnExport.Visibility = Visibility.Collapsed;
            //}

            // 如果不是 SV或QC，显示导出按钮 06/10/2011 edit
            if (!(FunctionClass.GetUserIdentity() == FunctionClass.UserIdentity.SV.ToString() ||
                    FunctionClass.GetUserIdentity() == FunctionClass.UserIdentity.QC.ToString()))
            {
                this.btnExport.Visibility = Visibility.Visible;
            }
            else
            {
                this.btnExport.Visibility = Visibility.Collapsed;
            }

        }

        /// <summary>
        /// Gets or sets vlaue of exportComand
        /// 导出命令 ExportComand
        /// </summary>
        public Command.ICommand ExportComand
        {
            get { return this.exportComand; }
            set { this.exportComand = value; }
        }

        /// <summary>
        /// Gets or sets value of queryCcommand
        /// 查询命令 QueryCcommand
        /// </summary>
        public Command.ICommand QueryCcommand
        {
            get { return this.queryCcommand; }
            set { this.queryCcommand = value; }
        }
        /// <summary>
        /// 变量初始化方法  InitField
        /// </summary>
        private void InitField()
        {
            this.wcfLogClient = Wcf.Service.Log4;
            this.wcfCommonQueryClient = Wcf.Service.CommonQuery;

            this.unitSelect = new childWindow.UnitSelChildWin();
            this.errorMessbox = new childWindow.MessageBox();
        }

        /// <summary>
        /// UNIT 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnUnitSelect_Click(object sender, RoutedEventArgs e)
        {
            writeWhereLog();
            this.btnUnitSelect.IsEnabled = false;

            this.queryCcommand.Exec();
        }

        /// <summary>
        /// 导出按钮 点击事件 BtnExport_Click
        /// </summary>
        /// <param name="sender">Sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            writeWhereLog();
            this.btnExport.IsEnabled = false;

            this.exportComand.Exec();
        }

        #region  页面载入
        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void USEfficSelContainer_Loaded(object sender, RoutedEventArgs e)
        {
            this.btnOPID.IsEnabled = true;

            this.dpDateFrom.SelectedDate = DateTime.Now.AddDays(-1);
            this.dpDateTo.SelectedDate = DateTime.Now.Date;
        }
        #endregion 页面载入
        
        #region 组别查询
        /// <summary>
        /// 组别查询 (...按钮)
        /// BtnOPID_Click
        /// 如果当前SV只有一组，直接显示组名
        /// 如果当前SV或SSV有多组，弹出子窗体
        /// </summary>
        /// <param name="sender">Sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnOPID_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.btnOPID.IsEnabled = false;

                // 判断 当前登录的SV或是SSV的登录信息
                if (!String.IsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserName) || !String.IsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserRealName))
                {
                    string svId = FunctionClass.MyIsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserName, "");
                    string svName = FunctionClass.MyIsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserRealName, "");

                    // 调用 WCF服务
                    wcfCommonQueryClient.SelSvUnitInfoAsync(svId, svName);
                }
                else
                {
                    throw new Exception("当前用户信息有误");
                }
            }
            catch (Exception ex)
            {
                this.btnOPID.IsEnabled = true;

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 查询SV或SSV的组别(实现)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void wcfCommonQueryClient_SelSvUnitInfoCompleted(object sender, Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFCommonQueryRef.SelSvUnitInfoCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count <= 0)
                    {
                        throw new Exception(" wcfCommonQueryClient_SelSvUnitInfoCompleted 服务出错！");
                    }
                    //是SV（只有一个组别，不用显示子窗体，直接显示在tbOPID的TEXT上）
                    if (e.Result.Count == 1)
                    {
                        if (!String.IsNullOrEmpty(this.tbOPID.Text))
                        {
                            this.tbOPID.Text = string.Empty;
                        }

                        ClientDataList.CheckOpUnitList.Clear();
                        ClientDataList.CheckOpUnitList.Add(e.Result[0].Unit.ToString().Trim());

                        this.tbOPID.Text = "ALL --" + e.Result[0].Unit.ToString() + "Unit";
                        return;
                    }
                    //是SSV（有多个组别，显示子窗体）
                    if (e.Result.Count > 1)
                    {
                        // *************CheckBox********************//
                        // 动态生成CHECKBOX，并给CONTEXT赋值（组名）。
                        this.unitSelect.UnitWrapping.Children.Clear();


                        for (int i = 0; i < e.Result.Count; i++)
                        {
                            CheckBox cb = new CheckBox();
                            cb.Content = e.Result[i].Unit.ToString();
                            cb.IsChecked = false;
                            cb.Margin = new Thickness(10, 3, 0, 5);
                            this.unitSelect.UnitWrapping.Children.Add(cb);
                        }
                        // ***************************************** 

                        this.unitSelect.Title = "查询子窗体";
                        this.unitSelect.Show();
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 子窗体关闭事件
        /// OpidSelect_Closed
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void UnitSelect_Closed(object sender, EventArgs e)
        {
            try
            {
                this.btnOPID.IsEnabled = true;
                this.tbOPID.Text =string.Empty;

                this.unitSelect = sender as Common.Window.UnitSelChildWin;

                if (this.unitSelect.DialogResult == true)
                {

                    // 已选择的部分组号
                    // ClientDataList.CheckOpUnitList（全局） 返回被选中的UNIT信息
                    ClientDataList.CheckOpUnitList.Clear();

                    // **************CheckBox****************
                    // 判断哪个CHECKBOX是选中状态，并将值
                    // 传给ClientDataList.CheckOpUnitList
                    CheckBox checkbox;
                    for (int i = 0; i < this.unitSelect.UnitWrapping.Children.Count; i++)
                    {
                        checkbox = this.unitSelect.UnitWrapping.Children[i] as CheckBox;

                        // 如果类型不一致则返回null
                        if (checkbox != null && checkbox.IsChecked == true)
                        {
                            // 不用加引号和逗号
                            ClientDataList.CheckOpUnitList.Add(checkbox.Content.ToString().Trim());
                        }
                    }

                    if (ClientDataList.CheckOpUnitList.Count > 0)
                    {
                        StringBuilder sbUnit = new StringBuilder();
                        foreach (string strunit in ClientDataList.CheckOpUnitList)
                        {
                            sbUnit.Append(strunit);
                            sbUnit.Append("Unit");
                            sbUnit.Append(" ");
                        }

                        this.tbOPID.Text = "ALL -- " + sbUnit.ToString(); 
                    }
                    // **************************************
                }

                if (this.unitSelect.DialogResult == false)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + " 转换OPID时出错" + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }
        #endregion 组别查询

        #region 日期(DatePicker)

        /// <summary>
        /// 结束日期(DatePicker)
        /// DpDateTo_SelectedDateChanged
        /// </summary>
        /// <param name="sender">sender of obejct</param>
        /// <param name="e">e type of SelectionChangedEventArgs</param>
        private void DpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dpDateTo == null || dpDateTo.SelectedDate == null)
            {
                return;
            }
            else
            {
                this.dpDateTo.Text = this.dpDateTo.SelectedDate.Value.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 开始日期(DatePicker)
        /// 防止选错时，出现BUG
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectionChangedEventArgs</param>
        private void DpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dpDateFrom == null || dpDateFrom.SelectedDate == null)
            {
                return;
            }
            else
            {
                this.dpDateFrom.Text = this.dpDateFrom.SelectedDate.Value.ToString("yyyy-MM-dd");
            }
        }

        #endregion 日期(DatePicker)

        #region 记录用户选择的WHERE条件
        /// <summary>
        /// 记录用户选择的WHERE条件
        /// </summary>
        /// <returns></returns>
        /// <value>10/15/2010 Add </value>
        private void writeWhereLog()
        {
            StringBuilder sbWhereIntorLogs = new StringBuilder();
            try
            {
                //日志用
                sbWhereIntorLogs.Append(" 查询条件：");
                sbWhereIntorLogs.Append(" 开始日期：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.dpDateFrom.Text) == true ? " null" : this.dpDateFrom.Text);
                sbWhereIntorLogs.Append(" 结束日期：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.dpDateTo.Text) == true ? " null" : this.dpDateTo.Text);
                sbWhereIntorLogs.Append(" 稼动率类别：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.cbWorkEfficiency.SelectionBoxItem.ToString()) == true ? " null" : this.cbWorkEfficiency.SelectionBoxItem.ToString());
                sbWhereIntorLogs.Append(" Unit信息：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.tbOPID.Text) == true ? " null" : this.tbOPID.Text);
            }
            catch
            {
                WhereIntorLogs = string.Empty;
            }

            WhereIntorLogs = sbWhereIntorLogs.ToString();
        }

        #endregion 记录用户选择的WHERE条件
    }
}
